import SwiftUI

struct TestView: View {
    @State private var selectedTab = 0
    @EnvironmentObject var photoService: PhotoService
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // 顶部标签选择器
                Picker("测试类型", selection: $selectedTab) {
                    Text("配置").tag(0)
                    Text("测试").tag(1)
                    Text("调试").tag(2)
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding()
                
                // 内容区域
                TabView(selection: $selectedTab) {
                    GeocodingConfigView()
                        .tag(0)
                    
                    AppleGeocodingTestView()
                        .tag(1)
                    
                    DebugView()
                        .tag(2)
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            }
            .navigationTitle("测试工具")
        }
    }
}

// MARK: - 调试视图
struct DebugView: View {
    @EnvironmentObject var photoService: PhotoService
    @State private var debugInfo: String = ""
    
    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                // 调试信息显示
                VStack(alignment: .leading, spacing: 8) {
                    Text("调试信息")
                        .font(.headline)
                    
                    Text(debugInfo.isEmpty ? "点击下方按钮获取调试信息" : debugInfo)
                        .font(.caption)
                        .foregroundColor(.secondary)
                        .padding()
                        .background(Color(.systemGray6))
                        .cornerRadius(8)
                }
                
                // 调试按钮
                VStack(spacing: 12) {
                    Button("检查照片加载状态") {
                        debugPhotoLoadingStatus()
                    }
                    .buttonStyle(.borderedProminent)
                    
                    Button("重新加载所有照片") {
                        Task {
                            await photoService.loadAllPhotos()
                        }
                    }
                    .buttonStyle(.bordered)
                    
                    Button("清除所有缓存") {
                        photoService.clearAllCache()
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.red)
                    
                    Button("检查持久化状态") {
                        photoService.checkPersistenceStatus()
                    }
                    .buttonStyle(.bordered)
                    
                    // 🚀 新增：照片解析优化按钮
                    Divider()
                        .padding(.vertical, 8)
                    
                    Text("照片解析优化")
                        .font(.headline)
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    Button("A. 打印一张未知地址的照片信息") {
                        photoService.printUnknownPhotoInfo()
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.blue)
                    
                    Button("B. 按优先级解析单张照片") {
                        Task {
                            await photoService.parseSinglePhotoWithPriority()
                        }
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.green)
                    
                    Button("C. 解析单张照片并保存到缓存") {
                        Task {
                            await photoService.parseAndSaveSinglePhoto()
                        }
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.orange)
                    
                    Button("D. 将缓存数据落地持久化") {
                        photoService.persistCacheData()
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.purple)
                    
                    Button("E. 刷新地点轴分组UI") {
                        photoService.refreshLocationAxisUI()
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.red)
                    
                    Button("强制刷新UI（父子节点分组）") {
                        photoService.forceRefreshLocationGroups()
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.red)
                    .padding(.vertical, 4)
                    Text("此按钮无条件强制刷新所有分组数据，确保UI与数据完全同步。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("清空UI节点（清除所有父子节点）") {
                        photoService.clearAllLocationGroups()
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.orange)
                    .padding(.vertical, 4)
                    Text("此按钮清空所有分组缓存，强制UI重新加载分组数据。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    // 🚀 新增：测试新地点轴视图
                    Divider()
                        .padding(.vertical, 8)
                    
                    Text("新地点轴视图测试")
                        .font(.headline)
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    Button("测试新地点轴视图") {
                        // 导航到新地点轴视图
                        print("📍 [测试] 准备测试新地点轴视图")
                        // 发送通知，让主界面切换到新视图
                        NotificationCenter.default.post(name: NSNotification.Name("ShowNewLocationAxis"), object: nil)
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.green)
                    .padding(.vertical, 4)
                    Text("测试重构后的新地点轴视图，使用MVVM架构。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("打印持久化分组数据") {
                        // 创建临时服务实例来打印数据
                        let service = LocationGroupService()
                        service.printPersistenceData()
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.purple)
                    .padding(.vertical, 4)
                    Text("打印UserDefaults中保存的分组数据。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("打印缓存分组数据") {
                        // 创建临时服务实例来打印数据
                        let service = LocationGroupService()
                        service.printCacheData()
                    }
                    .buttonStyle(.bordered)
                    .foregroundColor(.orange)
                    .padding(.vertical, 4)
                    Text("打印内存中的分组缓存数据。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("迁移持久化数据格式") {
                        // 创建临时服务实例来迁移数据
                        let service = LocationGroupService()
                        service.migratePersistenceData()
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.red)
                    .padding(.vertical, 4)
                    Text("将旧格式的持久化数据迁移到新格式（使用ID而不是字符串）。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("调试LocationGroupService") {
                        // 创建临时服务实例来调试分组
                        let service = LocationGroupService()
                        service.debugCurrentGroups(from: photoService.photos)
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.purple)
                    .padding(.vertical, 4)
                    Text("调试当前分组状态，显示所有分组信息。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("调试数据指纹") {
                        // 创建临时服务实例来调试数据指纹
                        let service = LocationGroupService()
                        service.debugDataFingerprint(from: photoService.photos)
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.orange)
                    .padding(.vertical, 4)
                    Text("详细分析数据指纹，显示照片统计信息。")
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Button("🔍 检查地理编码数据") {
                        print("🔍 === 按钮：检查地理编码数据 ===")
                        let locationGroupService = LocationGroupService()
                        locationGroupService.debugGeocodedPhotoData(from: photoService.photos)
                    }
                    .buttonStyle(.bordered)
                    .padding(.horizontal)
                    
                    Button("📋 打印已知解析地址") {
                        print("📋 === 按钮：打印已知解析地址 ===")
                        photoService.printKnownAddresses()
                    }
                    .buttonStyle(.bordered)
                    .padding(.horizontal)
                    
                    Button("🚀 批量解析100张未知照片") {
                        print("🚀 === 按钮：批量解析100张未知照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotos(count: 100)
                        }
                    }
                    .buttonStyle(.bordered)
                    .padding(.horizontal)
                    
                    Button("⚡ 多线程批量解析100张照片") {
                        print("⚡ === 按钮：多线程批量解析100张照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotosConcurrent(count: 100, maxConcurrency: 5)
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.blue)
                    .padding(.horizontal)
                    
                    Button("⚡ 多线程批量解析500张照片") {
                        print("⚡ === 按钮：多线程批量解析500张照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotosConcurrent(count: 500, maxConcurrency: 5)
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.green)
                    .padding(.horizontal)
                    
                    Button("⚡ 多线程批量解析1000张照片") {
                        print("⚡ === 按钮：多线程批量解析1000张照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotosConcurrent(count: 1000, maxConcurrency: 5)
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.orange)
                    .padding(.horizontal)
                    
                    // 🚀 新增：优化版多线程批量解析按钮
                    Divider()
                        .padding(.vertical, 8)
                    
                    Text("优化版多线程批量解析")
                        .font(.headline)
                        .frame(maxWidth: .infinity, alignment: .leading)
                    
                    Button("🚀 优化版批量解析100张照片") {
                        print("🚀 === 按钮：优化版批量解析100张照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotosOptimized(count: 100)
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.purple)
                    .padding(.horizontal)
                    
                    Button("🚀 优化版批量解析500张照片") {
                        print("🚀 === 按钮：优化版批量解析500张照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotosOptimized(count: 500)
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.indigo)
                    .padding(.horizontal)
                    
                    Button("🚀 优化版批量解析1000张照片") {
                        print("🚀 === 按钮：优化版批量解析1000张照片 ===")
                        Task {
                            await photoService.batchParseUnknownPhotosOptimized(count: 1000)
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.red)
                    .padding(.horizontal)
                    
                    Button("🧪 测试腾讯高德API失败原因") {
                        print("🧪 === 按钮：测试腾讯高德API失败原因 ===")
                        Task {
                            await photoService.testTencentAMapAPIFailures()
                        }
                    }
                    .buttonStyle(.bordered)
                    .padding(.horizontal)
                    
                    Button("🔐 测试腾讯API签名修复") {
                        print("🔐 === 按钮：测试腾讯API签名修复 ===")
                        Task {
                            await photoService.testTencentAPISignatureFix()
                        }
                    }
                    .buttonStyle(.borderedProminent)
                    .foregroundColor(.green)
                    .padding(.horizontal)
                }
            }
            .padding()
        }
    }
    
    private func debugPhotoLoadingStatus() {
        photoService.debugPhotoLoadingStatus()
        
        // 获取调试信息
        let totalPhotos = photoService.totalPhotoCount
        let loadedPhotos = photoService.photos.count
        let photosWithLocation = photoService.photos.filter { $0.location != nil }.count
        let photosWithoutLocation = photoService.photos.filter { $0.location == nil }.count
        
        // 使用新的LocationGroupService而不是PhotoService的旧分组方法
        let locationGroupService = LocationGroupService()
        let groups = locationGroupService.getLocationGroups(from: photoService.photos)
        let groupInfo = groups.map { "\($0.city): \($0.totalPhotos)张" }.joined(separator: "\n")
        
        debugInfo = """
        照片加载状态:
        - 本机总照片数: \(totalPhotos)
        - 已加载照片数: \(loadedPhotos)
        - 有地理信息: \(photosWithLocation)
        - 无地理信息: \(photosWithoutLocation)
        
        分组信息:
        \(groupInfo)
        """
    }
}

#Preview {
    TestView()
        .environmentObject(PhotoService())
} 